import { observable, action } from 'mobx';
import permissionApi from '@/api/permissionApi';
import { PaginateConfig, PaginateResult } from '@/type/Shared';
import { Permission, Role } from '@/type/Permission';

export default class PermissionStore {
    @observable permissions: Permission[] = [];
    @observable roles: Role[] = [];

    @action
    public async hasPermission(permission: string): Promise<boolean> {
        return permissionApi.hasPermission(permission);
    }

    @action
    public async getRoles(config: PaginateConfig): Promise<PaginateResult<Role[]>> {
        const paginated = await permissionApi.getRoles(config);
        this.roles = paginated.data;
        return paginated;
    }

    @action
    public async getRole(id: number): Promise<Role> {
        return permissionApi.getRole(id);
    }

    @action
    public async saveRole(role: Role, permissions: number[]) {
        if (role.id) return this.updateRole(role, permissions);
        return this.createRole(role, permissions);
    }

    @action
    public async createRole(role: Role, permissions: number[]): Promise<Role> {
        return permissionApi.createRole(role, permissions);
    }

    @action
    public async updateRole(role: Role, permissions: number[]): Promise<Role> {
        return permissionApi.updateRole(role, permissions);
    }

    @action
    public async deleteRole(id: number): Promise<boolean> {
        return permissionApi.deleteRole(id);
    }

    @action
    public async getPermissions(config: PaginateConfig): Promise<PaginateResult<Permission[]>> {
        const paginated = await permissionApi.getPermissions(config);
        this.permissions = paginated.data;
        return paginated;
    }
}
